<template>
  <div
    class="m-upload-empty"
    :style="{ width: `${width}px`, height: `${height}px` }"
  >
    <div class="m-default"><slot name="icon"></slot></div>
    <img v-if="bgImage" :src="bgImage" :alt="alt" class="m-default-img" />

    <input
      v-if="multiple"
      ref="input"
      type="file"
      :accept="accept"
      multiple
      @change="onChange"
    />
    <input v-else ref="input" type="file" :accept="accept" @change="onChange" />
  </div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import axios from 'axios'
import { Toast } from 'vant'

const busTypeMap = {
  6: 'nuxtjs/',
}

export default defineComponent({
  name: 'UploadEmpty',
  props: {
    multiple: {
      type: Boolean,
    },
    accept: {
      type: String,
    },
    bgImage: {
      type: String,
    },
    width: {
      type: [Number, String],
    },
    height: {
      type: [Number, String],
    },
    maxSize: {
      type: Number,
    },
    lenMax: {
      type: Number,
    },
    uploadText: {
      type: String,
    },
    busType: {
      type: Number,
    },
    alt: {
      type: String,
    },
  },
  methods: {
    onChange(event) {
      let { files } = event.target
      if (!files || !files.length) return

      files = [].slice.call(files, 0)
      // todo
      Promise.all(files.map(this.readFile)).then((contents) => {
        let overSize = false
        const payload = files.map((file, index) => {
          if (this.maxSize && file.size > this.maxSize) overSize = true
          return {
            file: files[index],
            content: contents[index],
          }
        })
        this.onAfterRead(payload, overSize)
      })
    },
    readFile(file) {
      return new Promise((resolve) => {
        const reader = new FileReader()
        reader.onload = (event) => {
          resolve(event.target.result)
        }
        reader.readAsDataURL(file)
      })
    },
    onAfterRead(files, overSize) {
      if (overSize) {
        Toast(`请选择小于 ${this.fileSize(this.maxSize)} 的文件`)
        this.uploaded()
        return
      }

      if (this.lenMax < files.length) {
        Toast(`请选择不超过 ${this.lenMax} 个文件`)
        this.uploaded()
        return
      }

      const uploadQueues = files.map(async (rawFile) => {
        const { file, content } = rawFile
        console.log(content, file.name)
        const rs = await axios.post(
          'https://api.jsvue.cn/user-center/user/getUploadToken',
          {
            fileKey: busTypeMap[this.busType] + file.name,
            businessType: this.busType,
          }
        )
        console.log(rs)
      })

      Toast.loading({
        message: '上传中...',
        forbidClick: true,
        loadingType: 'spinner',
      })
      Promise.all(uploadQueues)
        .then((data) => {
          Toast.clear()
          this.$emit('upload', data)
          this.uploaded()
        })
        .catch((err) => {
          console.error(err)
          Toast.clear()
          this.uploaded()
        })
    },
    uploaded() {
      this.$refs.input && (this.$refs.input.value = '')
    },
    fileSize(size) {
      if (typeof size !== 'number') return '0K'
      if (size > 1048576) size = (size / 1048576).toFixed(2) + 'M'
      else if (size > 1024) size = (size / 1024).toFixed(2) + 'K'
      return size
    },
  },
})
</script>
<style lang="less" scoped>
.m-default {
  position: relative;
  z-index: 2;
  height: inherit;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  &-icon {
    color: #ccc;
    font-size: 30px;
  }
  &-img {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  span {
    font-size: 12px;
    line-height: 24px;
    color: #666;
  }
}
</style>
